package com.zuijin.vue2blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zuijin.vue2blog.dto.UserComDetails;
import com.zuijin.vue2blog.entity.Role;
import com.zuijin.vue2blog.entity.UserCom;
import com.zuijin.vue2blog.service.UserComDetailsService;
import com.zuijin.vue2blog.service.UserComService;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 实现 UserComDetailsService
 * </p>
 *
 * @author 醉瑾
 * @since 2022-04-23
 */
@Service
public class UserComDetailsServiceImpl implements UserComDetailsService {
    @Lazy
    @Resource
    UserComService userComService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        QueryWrapper<UserCom> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserCom::getUsername, username);
        UserCom userCom = userComService.getOne(queryWrapper);

        System.out.println("UserComDetailsServiceImpl-loadUserByUsername: " + userCom);

        if (userCom != null) {
            // TODO 增加角色和权限信息
            List<Role> roles = new ArrayList<>();
            Role role = new Role();
            role.setRoleName("admin");
            roles.add(role);
            return new UserComDetails(userCom, roles);
        }
        throw new UsernameNotFoundException("用户名或密码错误！");
    }
}
